<template>
	<base-upload :options="options" v-model="val" ref="baseUpload" :class="options['class']">
		<i v-if="options['list-type'] === 'picture-card'" class="el-icon-plus" slot="button"></i>
		<el-button
			v-else
			class="upload-button"
			slot="button"

			:size="button.size"
			:type="button.type"
			:icon="button.icon"
		>{{button.text}}
		</el-button>
		<div class="upload-tip el-upload__tip" v-if="options.tip" slot="tip">{{options.tip}}</div>
	</base-upload>
</template>

<script>

	import BaseUpload from './base-upload.vue'

	export default {
		components: {BaseUpload},
		props: {
			options: {
				default: Object,
				required: true
			},
			value: {
				// [url1, url2, url3]
				type: String | Array,
				required: true
			}
		},
		data() {
			return {}
		},
		computed: {
			val: {
				get() {
					let value = [];
					if (Array.isArray(this.value)) {
						value = this.value.map(url => {
							return {url: url}
						})
					} else if(this.value) {
						value.push({url: this.value})
					}
					if(this.options['list-type'] === 'picture-card'){
						const uploadDiv = this.$refs.baseUpload && this.$refs.baseUpload.$el && this.$refs.baseUpload.$el.querySelector('.el-upload--picture-card')
						if(uploadDiv){
							uploadDiv.style.display = (!this.options.limit || this.options.limit>value.length)?'inline-block':'none'
						}
					}
					return value;
				},
				set(value) {
					// 多文件时仍然有问题
					// element的逻辑是多文件的时候请求多次接口，将结果合并, filelist: [{response}, {response}]
					let urls = [];
					urls = urls.concat(value.map(fileItem => {
						return fileItem.response?fileItem.response.data.url:fileItem.url
					}))
					if(this.options.limit===1){
						urls = urls.length>0?urls[0]:'';
					}
					this.$emit("input", urls)
				},
			},
			button() {
				return Object.assign({
					size: 'small',
					type: 'primary',
					text: '上传',
					icon: 'el-icon-upload'
				}, this.options.button || {})
			}
		},
		methods:{
			clearFiles () {
				this.$refs['baseUpload'].clearFiles()
			},
			abort () {
				this.$refs['baseUpload'].abort()
			}
		}
	}
</script>

<style scoped>
	.upload-button {
		position: relative;
		right: 0;
	}

	.upload-tip {
		margin-left: 12px;
	}
</style>

